/*
 * @Autor: dingxiaolin
 * @Date: 2020-11-04 22:48:46
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2020-11-05 00:37:28
 */
package com.dxl.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dxl.annotation.SkipToken;
import com.dxl.config.QiNiuCloudConfiguration;
import com.dxl.entity.*;
import com.dxl.entity.groups.Insert;
import com.dxl.entity.groups.Update;
import com.dxl.enums.ResultEnums;
import com.dxl.enums.SexEnum;
import com.dxl.handler.MessageSourceHandler;
import com.dxl.service.MybatisService;
import com.dxl.utils.JwtUtil;
import com.dxl.utils.QiNiuCloudUtil;
import com.dxl.utils.ResDataUtil;
import com.dxl.utils.excel.ExcelListener;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Api(tags = "用户模块")
@RestController
@RequestMapping("/user")
@Slf4j
@Validated
public class AdminController {
    @Autowired //省去了get set new
    private MybatisService mybatisService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private MessageSourceHandler messageSourceHandler;
    /**
     * 登录并获取token
     * @param userReq
     * @return
     */
    @SkipToken
    @ApiOperation("登录")
    @ResponseBody
    @PostMapping("/login")
    public ResponseData login(@Valid @RequestBody UserReq userReq) {
        LoginRes loginRes = mybatisService.loginQuery(userReq);
        if(loginRes!=null){
            JSONObject userInfo=new JSONObject();
            System.out.println(loginRes.getId());
            String token = JwtUtil.sign(loginRes.getId());
            userInfo.put("userInfo",loginRes);
            userInfo.put("token",token);
            return ResDataUtil.success(userInfo);
        }else{
            return ResDataUtil.failure(ResultEnums.LOGIN_ERROR);
        }
    }

//    public Object login(@RequestBody Map<String, String> map) {
//        String userName = map.get("userName");
//        String passWord = map.get("passWord");
//        JSONObject jsonObject = new JSONObject();//阿里巴巴fastjson提供，标准json，key不能为空
//        String userId = UUID.randomUUID().toString();
//        // 生成签名
//        String token = JwtUtil.sign(userId);
//        Map<String, String> userInfo = new HashMap<>();//jdk提供，可以存key为空的值
//        userInfo.put("userId", userId);
//        userInfo.put("userName", userName);
//        userInfo.put("passWord", passWord);
//        jsonObject.put("token", token);
//        jsonObject.put("userDTO", userInfo);
//        return ResponseDataUtil.success(jsonObject);
//    }

    @ApiOperation("新增账号密码")
    @PostMapping("/addList")
    public ResponseData addList(@Validated(Insert.class) @Valid @RequestBody Admin admin) {
//        String userId = UUID.randomUUID().toString(); //普通uuid
//        admin.setUser_id(userId);//普通uuid
//        Long ID= IdWorker.getId(admin);  //自动生成雪花ID
//        int result = mybatisService.addList(admin);
        int result=mybatisService.insert(admin);
        System.out.println(result);

        return result > 0? ResDataUtil.success(
                messageSourceHandler.getMessage("add.user.success"),admin)
                : ResDataUtil.failure("新增账号失败");
    }

    @ApiOperation("删除账号密码")
    @DeleteMapping("/delList")
    // @PatchMapping("/delList/{id}") @PathVariable("id")
    public ResponseData delList(@ApiParam("ID号") @RequestParam(value = "id",required = false) @NotNull(message = "id不能为空") String id) {
        int result = mybatisService.deleteById(id);
        return result>0 ? ResDataUtil.success("删除成功") : ResDataUtil.failure("删除失败");
    }

    @ApiOperation("更新账号密码")
    @PatchMapping("/updateList")
    public ResponseData updateList(@Validated(Update.class) @RequestBody Admin admin) {
        int result=mybatisService.updateById(admin);
        return result>0 ? ResDataUtil.success("更新成功") : ResDataUtil.failure("更新失败");
    }

    //    @PostMapping("/getsessionId")
//    public Object getSessionId( @RequestBody Map<String,String> reqbody) {
//        String code = reqbody.get("code");
//        return code;
//    }
    @SkipToken
    @ResponseBody
    @ApiOperation("获取账号密码列表")
    @GetMapping("/getList")
    public ResponseData<List<Admin>> queryList(
            @ApiParam(value = "第几页",defaultValue = "1")  @RequestParam("pageNo") String pageNo,
            @ApiParam(value = "当前页个数",defaultValue = "2")  @RequestParam("pageSize") String pageSize,
            @ApiParam("性别") @RequestParam("sex") SexEnum sex
    ) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("sex",sex);
        Page<Admin> page = new Page<>(Integer.valueOf(pageNo),Integer.valueOf(pageSize));
        IPage<Admin> mybatisList = mybatisService.selectPage(page,wrapper);
        System.out.println("总页数"+mybatisList.getPages());
        System.out.println("总记录数"+mybatisList.getTotal());
        return ResDataUtil.success(mybatisList);
    }
    @ResponseBody
    @ApiOperation("获取管理员列表")
    @GetMapping("/getAdmin")
    public ResponseData<List<Admin>> queryAdmin(@RequestParam(value = "userName",required = false) @NotBlank(message = "管理员用户名不能为空") String userName) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name", userName);
        List<Admin> mybatisList = mybatisService.selectList(queryWrapper);
        return ResDataUtil.success(mybatisList);
    }
    @ResponseBody
    @ApiOperation("获取性别用户")
    @GetMapping("/getSex")
    public ResponseData<List<Admin>> querySex( @ApiParam("sex") @RequestParam("sex") SexEnum sex) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper();
        queryWrapper.eq("sex", sex).isNotNull("name");
        List<Admin> mybatisList = mybatisService.selectList(queryWrapper);
        return ResDataUtil.success(mybatisList);
    }

    /**
     * 导出 Excel（一个 sheet）
     * @throws
     */
    @ApiOperation(value = "导出 Excel", httpMethod = "GET")
    @GetMapping(value = "/exportExcel")
    public void exportWithOneSheet(HttpServletResponse response)  throws IOException {
        List<UserRes> users= mybatisService.queryList();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=demo.xlsx");
        EasyExcel.write(response.getOutputStream(), UserRes.class).sheet("模板").doWrite(users);
    }

    /**
     * 读取文件
     * @param file
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "读取 整个Excel(多个 sheet 需要 各个 sheet 字段相同)")
    @PostMapping(value = "/readExcel")
    public ResponseData<List<UserRes>> readAllExcel(MultipartFile file) throws IOException{
        ExcelListener excelListener = new ExcelListener();
        EasyExcel.read(file.getInputStream(), UserRes.class, excelListener).sheet().doRead();
        return ResDataUtil.success("读取成功",excelListener.getDatas());
    }

    /**
     * 限制上传图片的大小
     */
    private static Double Mb = QiNiuCloudConfiguration.MB;
    private static Double maxSize = QiNiuCloudConfiguration.maxSize;

    @ApiOperation(value = "上传图片|文件到七牛云")
    @PostMapping(value="/uploadToQiNiu")
    public ResponseData uploadImg(@RequestParam("file") MultipartFile file) {
        String result = "";
        if(!file.isEmpty()) {
            if (checkSize(file)) {
                return ResDataUtil.failure("超出限制大小");
            }
            try {
                //使用base64方式上传到七牛云
                return  QiNiuCloudUtil.uploadPicByBase64(file);
            } catch (Exception e) {
                e.printStackTrace();
                return ResDataUtil.failure("上传未知异常");
            }
        }else{
            return ResDataUtil.failure("文件为空");
        }
    }

    /**
     * 校验大小，上传图片不能大于指定大小
     * @param file
     * @return
     */
    public static boolean checkSize(MultipartFile file){
        //校验大小
        double ratio = file.getSize() / Mb;
        return ratio > maxSize ? true : false;
    }
    /**
     * 获取图片宽高拼接字符串：?width=100&height=200
     * @return
     */
    private String  getWidthAndHeight(MultipartFile file){
        try {
            InputStream inputStream = file.getInputStream();
            BufferedImage image = ImageIO.read(inputStream);
            if (null == image){
                return "ERROR";
            }
            int width = image.getWidth();
            int height = image.getHeight();
            return "?width="+width+"&height="+height;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
